//
//  HKMessageViewController.m
//  AQBPolice
//
//  Created by apple on 2017/7/4.
//  Copyright © 2017年 eight. All rights reserved.
//

#import "HKMessageViewController.h"

@interface HKMessageViewController ()

/**
 倒计时的计数器
 */
@property (nonatomic, assign) int count;

/**
 顶部的标签
 */
@property (weak, nonatomic) IBOutlet UILabel *topLabel;

/**
 验证码textField
 */
@property (weak, nonatomic) IBOutlet UITextField *msgTextField;

/**
 登录
 */
@property (weak, nonatomic) IBOutlet UIButton *loginButton;

/**
 重新获取验证码按钮
 */

@property (weak, nonatomic) IBOutlet UIButton *getNewMsgButton;

//timer对象
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation HKMessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //将手机号展示在顶部的label上
    self.topLabel.text = [NSString stringWithFormat:@"验证码已发送到%@", kPhoneNumber];
    
    //执行timer
    [self startTimer];
    
    // 监听文本输入框的改变
    // 1.拿到通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    // 2.注册监听
    [center addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:self.msgTextField];
    //按钮不能点击，颜色是灰色的
    self.loginButton.enabled = NO;
    [self.loginButton setBackgroundColor:HKColor(216, 216, 216)];
}

#pragma mark - 方法
//文本框改变
- (void)textChanged {
    //文本款有输入，按钮变成橙色
    if (self.msgTextField.text.length > 0) {
        self.loginButton.enabled = YES;
        [self.loginButton setBackgroundColor:HKColor(253, 151, 39)];
    }
}

//开始计时器
- (void)startTimer {
    //初始化倒计时的时间，初始化timer
    self.count = 60;
    self.getNewMsgButton.enabled = NO;
    [self.getNewMsgButton setTitle:[NSString stringWithFormat:@" %d秒后重新发送验证码 ",self.count] forState:UIControlStateDisabled];
    [self.getNewMsgButton setTitleColor:HKColor(216, 216, 216) forState:UIControlStateDisabled];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFired) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

//计时器执行，count计数减1
- (void)timeFired{
    self.count--;
    self.getNewMsgButton.titleLabel.text = [NSString stringWithFormat:@"%d秒后重新发送验证码",self.count];
    if (self.count == 0) {
        self.getNewMsgButton.enabled = YES;
        [self.getNewMsgButton setTitle:@"重新发送验证码" forState:UIControlStateNormal];
        [self.getNewMsgButton setTitleColor:HKColor(253, 191, 39) forState:UIControlStateNormal];
        //结束定时器
        [self.timer invalidate];
    }
}

#pragma mark - actions
//返回按钮点击，返回输入手机号界面
- (IBAction)backButtonClicked:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//登录按钮点击
- (IBAction)loginButtonClicked:(id)sender {
    //收起键盘
    [self.msgTextField resignFirstResponder];
    //访问网络进行验证码的比对
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/police/checkMessage/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    NSString *phoneStr = [NSString stringWithFormat:@"telephone=%@", kPhoneNumber];
    NSString *msgStr = [NSString stringWithFormat:@"&code=%@", self.msgTextField.text];
    request.HTTPBody=[[phoneStr stringByAppendingString:msgStr] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        if (data == nil) {
            [MBProgressHUD showError:@"网络错误" toView:self.view];
        }else {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            if ([dict[@"meta"] isEqual: @"success"]) {
                //保存警号
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:dict[@"policeInfo"][@"policeId"] forKey:@"getPoliceNumber"];
                [userDefaults setObject:dict[@"policeInfo"][@"name"] forKey:@"name"];
                //回到主线程进行界面的跳转
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
                    self.view.window.rootViewController = storyBoard.instantiateInitialViewController;
                    [MBProgressHUD showSuccess:@"登录成功" toView:self.view.window];
                });
            }else {
                //回到主线程提示验证码不正确
                dispatch_async(dispatch_get_main_queue(), ^{
                    [MBProgressHUD showError:@"验证码不正确" toView:self.view];
                });
            }
        }
    }];
    [task resume];
}

//点击按钮重新获取验证码
- (IBAction)getNewMagButtonClicked:(id)sender {
    //向后台发送短信重新获取验证码
    NSURLSession *session = [NSURLSession sharedSession];
    NSString *urlString = [baseURL stringByAppendingString:@"mobile/common/sendMessage/"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"telephone=%@", kPhoneNumber] dataUsingEncoding:NSUTF8StringEncoding];
    
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    }];
    [task resume];
    //重新调用定时器进行计时
    [self startTimer];
}

//点击空白处收起键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
